

import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.events.MouseEvent;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.filesystem.File;
import flash.utils.setTimeout;

import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import mx.collections.IList;
import mx.events.StateChangeEvent;



public var loginDB:SQLConnection;
public var loginDBStatement:SQLStatement;
[Bindable] public var loginCollection:ArrayCollection = new ArrayCollection();

private function initLoginDatabase():void
{
	loginDB = new SQLConnection();
	var dbFile:File = File.applicationStorageDirectory.resolvePath("login.db");
	loginDB.open(dbFile);
	loginDBStatement = new SQLStatement();
	loginDBStatement.sqlConnection = loginDB;
	
	loginDBStatement.itemClass = Login;
	loginDBStatement.addEventListener(SQLEvent.RESULT, handleResult);
	//dbStatement.addEventListener(SQLErrorEvent.ERROR, createError);
	
	loginDBStatement.text = "CREATE TABLE IF NOT EXISTS logins ( no INTEGER PRIMARY KEY AUTOINCREMENT, isStored TEXT, userIdx TEXT)";
	loginDBStatement.execute();
	
}

private function handleResult(event:SQLEvent):void
{
	var result:SQLResult = loginDBStatement.getResult();
	if (result != null) {  
		loginCollection = new ArrayCollection(result.data);
		try{
			isStored = loginCollection[0].isStored;
			userIdx = loginCollection[0].userIdx;
		}catch(e:Error){
			isStored = "FALSE";
			userIdx = "";
		}
	}
	
	//trace("handled");
	
	//trace(isChkedLogin.toString());
	if(isChkedLogin == false){
		//trace("chking");
		behaveProperLogin();
	}
	
	//trace("length of loginCollection is " + loginCollection.length);
	try{
		//trace("stored idx : " + loginCollection[0].userIdx);
	}catch(e:Error){}
	
	
}



private function getLogins():void
{
	loginDBStatement.text = "SELECT * from logins";
	loginDBStatement.execute();
}

private function onSaveLogin():void{
	
	var login:Login = new Login();
	
	delLogin();
	
	login.isStored = "TRUE";
	login.userIdx = hooked_idx;
	
	addLogin(login);
}


private function addLogin(login:Login):void
{
	
	
	try{
		loginDBStatement.text = "INSERT into logins (isStored,userIdx) values('" +
		login.isStored + "','" +
		login.userIdx + "')";
	}catch(e:Error){trace(e.toString());}
	
	trace("adding idx = " + login.userIdx);
	
	isStored = login.isStored;
	userIdx = login.userIdx;
	
	loginDBStatement.execute();
}

private function delLogin():void
{
	var sqlDelete:String = "delete from logins";
	loginDBStatement.text = sqlDelete;
	loginDBStatement.execute();
	//getLogins();
	
	isStored = "FALSE";
	userIdx = "";
}
